import { BaseMenu } from './BaseMenu';
import { MenuConfig } from '../MenuManager';
import { Vector2D } from '../../utils/Vector2D';

interface SettingItem {
    name: string;
    type: 'slider' | 'toggle' | 'select';
    value: number | string;
    options?: string[];
    min?: number;
    max?: number;
}

export class SettingsMenu extends BaseMenu {
    private settings: SettingItem[] = [
        { name: '游戏速度', type: 'select', value: 'normal', options: ['slow', 'normal', 'fast'] },
        { name: '音量', type: 'slider', value: 0.5, min: 0, max: 1 },
        { name: '控制方式', type: 'select', value: 'keyboard', options: ['keyboard', 'touch'] },
        { name: '画质', type: 'select', value: 'medium', options: ['low', 'medium', 'high'] }
    ];

    private itemHeight: number = 60;
    private spacing: number = 30;
    private sliderWidth: number = 200;
    private activeItem: number = -1;

    constructor(config: MenuConfig) {
        super(config);
        this.initializeSettingsValues();
    }

    private initializeSettingsValues(): void {
        // 从配置中初始化设置值
        this.settings[0].value = this.config.speedLevel;
        this.settings[1].value = this.config.soundVolume;
        this.settings[2].value = this.config.controlType;
        this.settings[3].value = this.config.graphicsQuality;
    }

    public render(ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement): void {
        // 绘制返回按钮
        this.drawBackButton(ctx);

        // 绘制标题
        ctx.fillStyle = this.theme.textColor;
        ctx.font = 'bold 32px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('游戏设置', canvas.width / 2, 100);

        // 绘制设置项
        const startY = 180;
        this.settings.forEach((setting, index) => {
            const y = startY + index * (this.itemHeight + this.spacing);
            this.drawSettingItem(ctx, canvas.width / 2, y, setting, index === this.activeItem);
        });
    }

    public handleClick(x: number, y: number, canvas: HTMLCanvasElement): string | null {
        // 检查返回按钮点击
        if (this.isBackButtonClicked(x, y)) {
            return 'back';
        }

        // 检查设置项点击
        const startY = 180;
        this.settings.forEach((setting, index) => {
            const itemY = startY + index * (this.itemHeight + this.spacing);
            if (y >= itemY && y <= itemY + this.itemHeight) {
                this.handleSettingClick(x, y, setting, index, canvas);
            }
        });

        return null;
    }

    private handleSettingClick(x: number, y: number, setting: SettingItem, index: number, canvas: HTMLCanvasElement): void {
        const centerX = canvas.width / 2;

        if (setting.type === 'slider') {
            const sliderX = centerX - this.sliderWidth / 2;
            if (x >= sliderX && x <= sliderX + this.sliderWidth) {
                const percentage = (x - sliderX) / this.sliderWidth;
                const value = setting.min! + (setting.max! - setting.min!) * percentage;
                this.updateSettingValue(index, value);
            }
        } else if (setting.type === 'select') {
            const options = setting.options!;
            const optionWidth = 100;
            const totalWidth = options.length * optionWidth;
            const startX = centerX - totalWidth / 2;

            options.forEach((option, optionIndex) => {
                const optionX = startX + optionIndex * optionWidth;
                if (x >= optionX && x <= optionX + optionWidth) {
                    this.updateSettingValue(index, option);
                }
            });
        }
    }

    private updateSettingValue(index: number, value: number | string): void {
        this.settings[index].value = value;

        // 更新配置
        switch (index) {
            case 0: // 游戏速度
                this.config.speedLevel = value as 'slow' | 'normal' | 'fast';
                switch (value) {
                    case 'slow':
                        this.config.customSpeed = 3.0;
                        break;
                    case 'normal':
                        this.config.customSpeed = 5.0;
                        break;
                    case 'fast':
                        this.config.customSpeed = 8.0;
                        break;
                }
                break;
            case 1: // 音量
                this.config.soundVolume = value as number;
                break;
            case 2: // 控制方式
                this.config.controlType = value as 'keyboard' | 'touch';
                break;
            case 3: // 画质
                this.config.graphicsQuality = value as 'low' | 'medium' | 'high';
                break;
        }

        this.saveConfig();
    }

    public update(deltaTime: number): void {
        // 设置菜单可能不需要更新逻辑
    }

    private drawSettingItem(ctx: CanvasRenderingContext2D, centerX: number, y: number, setting: SettingItem, isActive: boolean): void {
        // 绘制设置项名称
        ctx.fillStyle = this.theme.textColor;
        ctx.font = '20px Arial';
        ctx.textAlign = 'right';
        ctx.fillText(setting.name, centerX - 150, y + this.itemHeight / 2);

        // 根据设置类型绘制控制器
        if (setting.type === 'slider') {
            this.drawSlider(ctx, centerX, y, setting);
        } else if (setting.type === 'select') {
            this.drawSelector(ctx, centerX, y, setting);
        }
    }

    private drawSlider(ctx: CanvasRenderingContext2D, centerX: number, y: number, setting: SettingItem): void {
        const sliderX = centerX - this.sliderWidth / 2;
        const sliderY = y + this.itemHeight / 2;

        // 绘制滑动条背景
        ctx.strokeStyle = this.theme.borderColor;
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.moveTo(sliderX, sliderY);
        ctx.lineTo(sliderX + this.sliderWidth, sliderY);
        ctx.stroke();

        // 绘制滑块
        const percentage = ((setting.value as number) - setting.min!) / (setting.max! - setting.min!);
        const handleX = sliderX + this.sliderWidth * percentage;
        
        ctx.fillStyle = this.theme.highlightColor;
        ctx.beginPath();
        ctx.arc(handleX, sliderY, 8, 0, Math.PI * 2);
        ctx.fill();
    }

    private drawSelector(ctx: CanvasRenderingContext2D, centerX: number, y: number, setting: SettingItem): void {
        const options = setting.options!;
        const optionWidth = 100;
        const totalWidth = options.length * optionWidth;
        const startX = centerX - totalWidth / 2;

        options.forEach((option, index) => {
            const x = startX + index * optionWidth;
            const isSelected = option === setting.value;

            // 绘制选项背景
            ctx.fillStyle = isSelected ? this.theme.highlightColor : this.theme.backgroundColor;
            ctx.strokeStyle = this.theme.borderColor;
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.roundRect(x, y + 10, optionWidth - 10, this.itemHeight - 20, 5);
            ctx.fill();
            ctx.stroke();

            // 绘制选项文本
            ctx.fillStyle = isSelected ? this.theme.backgroundColor : this.theme.textColor;
            ctx.font = '16px Arial';
            ctx.textAlign = 'center';
            ctx.fillText(option, x + (optionWidth - 10) / 2, y + this.itemHeight / 2);
        });
    }

    private drawBackButton(ctx: CanvasRenderingContext2D): void {
        const backButtonX = 50;
        const backButtonY = 50;

        ctx.fillStyle = this.theme.textColor;
        ctx.strokeStyle = this.theme.borderColor;
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.arc(backButtonX, backButtonY, 30, 0, Math.PI * 2);
        ctx.fill();
        ctx.stroke();

        // 绘制返回箭头
        ctx.beginPath();
        ctx.moveTo(backButtonX + 10, backButtonY);
        ctx.lineTo(backButtonX - 10, backButtonY);
        ctx.lineTo(backButtonX - 5, backButtonY - 5);
        ctx.moveTo(backButtonX - 10, backButtonY);
        ctx.lineTo(backButtonX - 5, backButtonY + 5);
        ctx.strokeStyle = '#FFFFFF';
        ctx.stroke();
    }

    private isBackButtonClicked(x: number, y: number): boolean {
        const backButtonX = 50;
        const backButtonY = 50;
        return Math.sqrt(Math.pow(x - backButtonX, 2) + Math.pow(y - backButtonY, 2)) <= 30;
    }
}